// \u4e00-\u9fa5] 中文验证规则
import validate from 'wechat-validate'

Page({
  behaviors: [validate],
  data: {
    idcardFrontUrl: '',
    idcardBackUrl: '',
    id: undefined,
    point: '',
    building: '',
    room: '',
    name: '',
    gender: '',
    mobile: '',
  },
  rules: {
    name: [
      { required: true, message: '请填写业主姓名!' },
      { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: '请检查业主姓名是否正确!' },
    ],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1\d{10}$/, message: '请检查手机号码是否正确!' },
    ],
    idcardFrontUrl: [{ required: true, message: '请上传身份证国徽面!' }],
    idcardBackUrl: [{ required: true, message: '请上传身份证照片面!' }],
  },
  onLoad({ id, point, building, room }) {
    if (id) {
      this.getDetail(id)
      wx.setNavigationBarTitle({ title: '编辑房屋信息' })
    } else {
      wx.setNavigationBarTitle({ title: '添加房屋信息' })
      this.setData({ point, building, room })
    }
  },
  async getDetail(id) {
    const res = await wx.http.get(`/room/${id}`)
    this.setData(res.data)
  },
  // goList() {
  //   wx.reLaunch({
  //     url: '/house_pkg/pages/list/index',
  //   })
  // },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
  // 选择身份证给图片上传
  async choosePicture(e) {
    const { type } = e.mark
    const { tempFiles } = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
    })

    if (tempFiles[0].size > 2 * 1024 * 1024) return wx.utils.toast('图片大小不能超过2M')

    const res = await wx.http.upload('/upload', {
      name: 'file',
      filePath: tempFiles[0].tempFilePath,
    })
    this.setData({ [type]: res.data.url })
  },
  // 提交房屋信息
  async onSubmit() {
    if (!this.validate()) return
    const { __webviewId__, status, ...body } = this.data
    const res = await wx.http.post('/room', body)
    if (res.code === 10000) return wx.utils.toast(res.message)
    // 回退
    wx.navigateBack({ delta: body.id ? 2 : 4 })
  },
})
